import CardFunctions from "../Common/CardFunctions";
import { GameData } from "../Data/GameData";
import { BlockType, PosType } from "../Data/GameEnum";
import Grid from "./Grid";
import UIManager from "../Manager/UIManager";
import GameManager from "../Manager/GameManager";
import AssetsManager from "../Manager/AssetsManager";
import { ItemData } from "../Data/Level/ItemData";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Block extends cc.Component {
    @property(cc.Node)
    normal: cc.Node = null;
    @property(cc.Sprite)
    icon: cc.Sprite = null;
    @property(cc.Label)
    Label_point: cc.Label = null;

    blockType: BlockType = BlockType.NORMAL;
    // posType: PosType = PosType.CONCTROL;

    x: number = 0;
    y: number = 0;
    length: number = 1;
    id: number = 0;
    color: number = 0;
    point: number;
    is装填 = false;
    is装填完成 = false;
    
    isDead: boolean = false;

    startPos;
    grid: Grid = null;

    canMove: boolean = true;
    newPosition: cc.Vec3;
    initPosition: cc.Vec3;

    create_x;

    // 初始化
    init(_blockType: BlockType, _posType: PosType, _x: number, _y: number, _point: number, _id: number) {
        this.blockType = _blockType;
        this.x = _x;
        this.create_x = this.x;
        this.y = _y;
        this.point = _point;
        this.id = _id;

        this.node.active = true;

        this.node.position = cc.v3(0, 0, 0);

        this.startPos = this.node.position;

        this.RefreshSprite();

        // this.AddListener();
    }

    async RefreshSprite() {
        const item_data = ItemData[this.id];
        this.icon.spriteFrame = AssetsManager.图片[item_data.icon];
        this.icon.sizeMode = cc.Sprite.SizeMode.TRIMMED;

        this.icon.node.color = new cc.Color().fromHEX(`#333333`);
        // this.icon.node.opacity = 255 * 0.8;
    }

    GetNodeWorldPostation(_node: cc.Node): cc.Vec3 {
        let pos: cc.Vec3 = cc.v3();
        if (_node.parent == null) {
            pos = cc.v3(_node.getPosition());
        } else {
            pos = cc.v3(_node.parent.convertToWorldSpaceAR(_node.getPosition()));
        }
        return pos;
    }

    AddListener() {
        // this.node.on(cc.Node.EventType.TOUCH_START, this.TOUCH_START, this);
        // this.node.on(cc.Node.EventType.TOUCH_MOVE, this.TOUCH_MOVE, this);
        // this.node.on(cc.Node.EventType.TOUCH_END, this.TOUCH_END, this);
        // this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.TOUCH_END, this);
    }

    async TOUCH_START(t) {
        if (!this.canMove) {
            return;
        }

        GameData.IsMouseDown = true;

        this.node.scale = 1;
        const location = t.getLocation();
        this.initPosition = this.node.position;
        GameData.StartPos = location;

        CardFunctions.SetAllGridCanPlaceForce(true);
        CardFunctions.SetAllGridCanPlaceByBlock(this);
        CardFunctions.RefreshAllGridCanPlace();
    }

    TOUCH_MOVE(t) {
        CardFunctions.AllGridSelect(false);

        if (!this.canMove) {
            return;
        }


        if (GameData.IsMouseDown === true) {
            const location = t.getLocation();

            GameData.CurrentPos = location;
            let diff = cc.v3(GameData.CurrentPos.sub(GameData.StartPos));

            let pos = cc.v3(this.initPosition.x + diff.x, this.initPosition.y + diff.y, this.initPosition.z);
            this.node.position = pos;

            let p1 = this.node.convertToWorldSpaceAR(cc.v2(0, 0));
            let p2 = UIManager.Instance.Root_grid.convertToNodeSpaceAR(p1);
            const x_new = this.GetXByX(p2.x);
            const y_new = this.GetXByY(p2.y);

            let grid: Grid = CardFunctions.GetGrid(x_new, y_new)
            if (grid && grid.block === null) {
                grid.Select(true);
            }

            CardFunctions.SetAllGridCanPlaceForce(true);
            CardFunctions.SetAllGridCanPlaceByBlock(this);
            CardFunctions.RefreshAllGridCanPlace();
        }
    }

    TOUCH_END() {
        CardFunctions.AllGridSelect(false);

        if (!this.canMove) {
            return;
        }

        GameData.IsMouseDown = false;

        let fun_list = [];
        let isTag: boolean = true;
        const block: Block = this;

        let p1 = block.node.convertToWorldSpaceAR(cc.v2(0, 0));
        let p2 = UIManager.Instance.Root_grid.convertToNodeSpaceAR(p1);

        const x_new = block.GetXByX(p2.x);
        const y_new = block.GetXByY(p2.y);

        let grid: Grid = CardFunctions.GetGrid(x_new, y_new)
        if (grid && grid.block === null && grid.canPlace === true) {
            let fun = () => {
                this.x = x_new;
                this.y = y_new;
                grid.block = block;
                block.grid = grid;
                block.node.parent = block.grid.node;
                block.node.position = cc.v3(0, 0, 0);
            }
            fun_list.push(fun);
        }
        else {
            isTag = false;
        }

        if (isTag) {
            for (let index = 0; index < fun_list.length; index++) {
                const fun = fun_list[index];
                fun();
            }
            this.canMove = false;

            let blockType = BlockType.NORMAL;
            let posType = PosType.下面操作台中;
            let x = this.create_x;
            let y = -1;
            let point = CardFunctions.GetRandomPoint();
            let id = CardFunctions.GetRandomId();
            CardFunctions.CreateBlock(blockType, posType, x, y, point, id);

            // GameManager.Main();
        }
        else {
            this.node.position = this.startPos;
            // this.node.scale = this.minScale;
        }

        CardFunctions.SetAllGridCanPlaceForce(true);
    }

    GetXByX(x_pos: number) {
        let x = (x_pos - (-GameData.W / 2 + this.node.width / 2)) / GameData.cell_width + 0.5;
        let x_int = Math.floor(x);
        return x_int;
    }

    GetXByY(y_pos: number) {
        let y = (y_pos - (-GameData.H / 2 + this.node.height / 2)) / GameData.cell_height + 0.5;
        let x_int = Math.floor(y);
        return x_int;
    }

    Destroy() {
        this.node.destroy();
    }

    // DestroyAnimation(callback: Function = null) {
    //     if (this.isDead) {
    //         return;
    //     }

    //     this.isDead = true;

    //     GamePanel.Instance.Refresh();

    //     let duration: number = 0.08;
    //     cc.tween(this.node)
    //         .delay(duration)
    //         .call(() => {
    //             this.node.scale = 0;
    //         })
    //         .delay(duration)
    //         .call(() => {
    //             this.node.scale = 1;
    //         })
    //         .delay(duration)
    //         .call(() => {
    //             this.node.scale = 0;
    //         })
    //         .delay(duration)
    //         .call(() => {
    //             this.node.scale = 1;
    //         })
    //         .delay(duration)
    //         .call(() => {
    //             this.node.scale = 0;
    //         })

    //         .call(async () => {
    //             const prefab = await bdlMgr.getRes<cc.Prefab>(Consts.BundleName.PREFAB, `ParticleSystem_explode`, cc.Prefab);

    //             let ParticleSystem_explode = cc.instantiate(prefab);
    //             ParticleSystem_explode.active = true;

    //             const sp = await bdlMgr.getRes<cc.SpriteFrame>(Consts.BundleName.SPRITE, `ui/shitou/shitou_00${this.color + 1}`, cc.SpriteFrame);
    //             const ps = ParticleSystem_explode.getComponent(cc.ParticleSystem);
    //             ps.spriteFrame = sp;

    //             ParticleSystem_explode.parent = UIManager.Instance.Root_effect;
    //             const p2 = UIManager.Instance.Root_effect.convertToNodeSpaceAR(this.node.convertToWorldSpaceAR(cc.Vec2.ZERO));

    //             ParticleSystem_explode.setPosition(p2);

    //             this.node.destroy();
    //             if (callback) {
    //                 callback();
    //             }
    //         })
    //         // .delay(0.01)
    //         // .call(() => {
    //         //     this.node.destroy();
    //         //     if (callback) {
    //         //         callback();
    //         //     }
    //         // })
    //         .start();
    // }
}